package testconfig

import (
	"bytes"
	"context"
	"encoding/json"
	"net/http"

	"yunzhan/alert-server/internal/svc"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type TestWeChatLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewTestWeChatLogic 微信测试
func NewTestWeChatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TestWeChatLogic {
	return &TestWeChatLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TestWeChatLogic) TestWeChat(req *types.TestWeChatRequest) (*types.TestResponse, error) {
	// 检查是否提供了微信配置
	if len(req.Config) == 0 {
		return &types.TestResponse{
			Success: 500,
			Message: "未提供微信配置",
		}, nil
	}

	config := req.Config[0] // 假设只有一个配置，取第一个

	// 准备发送微信消息的 payload
	payload := map[string]interface{}{
		"touser":  config.ToUser,
		"msgtype": "text",
		"text": map[string]string{
			"content": config.Message,
		},
	}
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return &types.TestResponse{
			Success: 500,
			Message: "负载序列化失败",
		}, err
	}

	// 发送HTTP请求到微信服务提供商
	url := "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + config.AccessToken // 假设需要提前获取AccessToken
	response, err := http.Post(url, "application/json", bytes.NewBuffer(payloadBytes))
	if err != nil {
		return &types.TestResponse{
			Success: 500,
			Message: "发送请求到微信服务提供商失败",
		}, err
	}
	defer response.Body.Close()

	// 检查响应状态
	if response.StatusCode != http.StatusOK {
		return &types.TestResponse{
			Success: 500,
			Message: "微信服务提供商响应非200状态",
		}, nil
	}

	return &types.TestResponse{
		Success: 200,
		Message: "微信消息发送成功",
	}, nil
}
